package server

import (
	"encoding/json"
	"fmt"
	"net"
	"os"
	"stargazer/xnat/xnetd/xutil"
)

type TCPServer struct {
	connList []*net.Conn
	listener net.Listener
	ConnChan chan *net.Conn
	// channelMap map[string]*chan []byte
}

// var ConnChan chan *net.Conn

type User struct {
	Username string
	Password string
}

func handleConnection(conn net.Conn, c chan []byte) {

}

func AuthencatieUser(conn *net.Conn) (isOk bool, username string) {
	buf := make([]byte, 1024)
	l, err := (*conn).Read(buf)
	var u User
	err = json.Unmarshal(buf[:l], &u)
	if err != nil {
		fmt.Println(err.Error())
	}
	dbutil := xutil.GetInstance()
	c := make(chan bool, 1)
	go dbutil.IsUserExist(u.Username, c)
	isOk = <-c
	if isOk {
		username = u.Username
		fmt.Println("login:  " + u.Username)
		(*conn).Write([]byte("succeed"))
		return
	}
	fmt.Println("login failed")
	(*conn).Write([]byte("fail"))

	return
}

func (server *TCPServer) Close() {
	server.listener.Close()
}

func (server *TCPServer) RunTCPServer() {
	fmt.Println("tcp server running at 8080")
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		println(err.Error())
		os.Exit(1)
	}
	server.listener = listener
	for {
		conn, err := listener.Accept()
		if err != nil {
			println(err.Error())
		}
		// append(server.connList, conn)
		// c := make(chan []byte)
		server.ConnChan <- &conn
		// go handleConnection(conn, c)
	}
}
